package ch.ethz.group3.myalbum.client;

import ch.ethz.group3.myalbum.client.utils.Global;
import ch.ethz.group3.myalbum.shared.TokenModel;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;

public class LoginWindow extends Window {

	private DynamicForm form;
	private TextItem tokenForm;
	private PictureServiceAsync pictureService = GWT
			.create(PictureService.class);

	public LoginWindow() {
		setTitle("Flickr OAuth Login");
		setWidth("20%");
		setHeight("10%");
		setShowModalMask(true);
		setIsModal(true);
		setShowMinimizeButton(false);
		setShowResizer(false);
		setShowCloseButton(false);
		setCanDragReposition(false);
		hideContextMenu();
		centerInPage();

		form = new DynamicForm();
		form.setHeight100();
		form.setWidth100();
		form.setPadding(15);
		form.setLayoutAlign(VerticalAlignment.TOP);

		tokenForm = new TextItem("EnterToken", "Enter Token:");
		form.setFields(tokenForm);
		tokenForm.addKeyPressHandler(new KeyPressHandler() {

			@Override
			public void onKeyPress(KeyPressEvent event) {
				if (event.getKeyName().equals("Enter")) {
					pictureService.verify(tokenForm.getValueAsString(),
							Global.requestToken,
							new AsyncCallback<TokenModel>() {

								@Override
								public void onSuccess(TokenModel result) {
									Global.accessToken = result;
									hide();
								}

								@Override
								public void onFailure(Throwable caught) {
									hide();
									SC.warn(caught.getMessage());
								}
							});
				}
			}
		});

		addItem(form);
	}

}
